package com.example.agenda.presenter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;

import com.example.agenda.CadastroActivity;
import com.example.agenda.view.ContactsView;
import com.example.vo.ContactDetails;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ContactsPresenter {

	private Context mContext;
	private ContactsView contactsView;
	private List<ContactDetails> contactDetailsList;

	public ContactsPresenter(ContactsView contactsView) {
		this.contactsView = contactsView;
		this.mContext = contactsView.asWidget();
	}

	public void go() {
		bind();
		fetchContactDetails();
	}

	private void bind() {
		contactsView.getButtontDel().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				deleteSelectedContacts();
			}
		});

		contactsView.getButtontAdd().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, CadastroActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_SINGLE_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);

				mContext.startActivity(intent);
			}
		});
	}

	public void sortContactDetails() {

		// Yes, we could use a more optimized method of sorting, but the
		// point is to create a test case that helps illustrate the higher
		// level concepts used when creating MVP-based applications.
		//
		for (int i = 0; i < contactDetailsList.size(); ++i) {
			for (int j = 0; j < contactDetailsList.size() - 1; ++j) {
				if (contactDetailsList
						.get(j)
						.getDisplayName()
						.compareToIgnoreCase(
								contactDetailsList.get(j + 1).getDisplayName()) >= 0) {
					ContactDetails tmp = contactDetailsList.get(j);
					contactDetailsList.set(j, contactDetailsList.get(j + 1));
					contactDetailsList.set(j + 1, tmp);
				}
			}
		}
	}

	private void deleteSelectedContacts() {
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();

		Gson gson = new Gson();

		try {
			HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(
					"http://10.0.2.2:8080/Agenda-service/contacts/");

			httpDelete.setEntity(new StringEntity(gson.toJson(contactsView
					.getSelectedRows())));
			httpDelete.setHeader("Accept", "application/json");
			httpDelete.setHeader("Content-type", "application/json");

			HttpResponse response = httpClient
					.execute(httpDelete, localContext);
			HttpEntity entity = response.getEntity();

			InputStream is = entity.getContent();

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));

			TypeToken<List<ContactDetails>> token = new TypeToken<List<ContactDetails>>() {
			};

			contactDetailsList = gson.fromJson(reader, token.getType());

			sortContactDetails();

			contactsView.setData(contactDetailsList);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void fetchContactDetails() {
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpGet httpGet = new HttpGet(
				"http://10.0.2.2:8080/Agenda-service/contacts");
		try {
			HttpResponse response = httpClient.execute(httpGet, localContext);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));

			TypeToken<List<ContactDetails>> token = new TypeToken<List<ContactDetails>>() {
			};

			Gson gson = new Gson();

			contactDetailsList = gson.fromJson(reader, token.getType());

			sortContactDetails();

			contactsView.setData(contactDetailsList);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
		public static final String METHOD_NAME = "DELETE";

		public String getMethod() {
			return METHOD_NAME;
		}

		public HttpDeleteWithBody(final String uri) {
			super();
			setURI(URI.create(uri));
		}

		public HttpDeleteWithBody(final URI uri) {
			super();
			setURI(uri);
		}

		public HttpDeleteWithBody() {
			super();
		}
	}
}
